package org.jeecg.modules.quartz.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrls {
    //post请求方式
    public static String doPost(String path, String data) {
        return invoke(path, data, "POST");
    }

    //put请求方式
    public static String doPut(String path, String data) {
        return invoke(path, data, "PUT");
    }

    //delete请求方式
    public static String doDelete(String path, String data) {
        String response = null;
        try {
            URL url = new URL(path + "?" + data);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("DELETE");
            connection.connect();
            if (200 == connection.getResponseCode()) {
                BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = bf.readLine()) != null) {
                    sb.append(line).append(System.getProperty("line.separator"));
                }
                bf.close();
                connection.disconnect();
                response = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    public static String invoke(String path, String data, String style) {
        String response = null;
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod(style);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.connect();
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            dataout.write(data.getBytes("utf-8"));
            dataout.flush();
            dataout.close();
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();
            connection.disconnect();
            response = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
